var tools = "";

var pagePath = $("#pagePath").val();
var resourcePath = $("#resourcePath").val();

$(function(){
	$("input").attr("maxlength","80");
	$("textarea").attr("maxlength","1000");
	//任务列表加载
	$("#dataTable").initTable({
        url:pagePath+"/cleanTask/cleanPipeLineManager/getCleanPipeLineManagerIndex.json",
        columnData:[
            {title:tableOpt.getCheckBox(null),name:"ID",width:"",align:"center",format:function(json){return tableOpt.getCheckBox(json.ID)}},        
            {title:"任务名称",name:"TASKNAME",width:"10%",align:"center"},
            {title:"管道名称",name:"LINENAME",width:"15%",align:"center"},
            {title:"发球点",name:"FROMPIG",width:"10%",align:"center"},
            {title:"收球点",name:"TOPIG",width:"10%",align:"center"},
            {title:"计划清管时间",name:"PLANPAGDATETIME",width:"15%",align:"center"},
            {title:"创建人",name:"CREATEUSER",width:"10%",align:"center"},
            {title:"状态",name:"STAUS",width:"10%",align:"center",format:function(json){ return tableOpt.getState(json.STAUS)}},
            {title:"编辑/发布/附件",name:"ID",width:"15%",align:"center",format:function(json){return tableOpt.getOpt(json.ID)}}
        ],
        selectDataNow:true,
        afterLoadTable:addStateCss,
    });
	
});

function addStateCss(){
	var t = $("#dataTable").find("tr[dname='dataRow_']");
	for (var i = 0; i < t.length; i++) {
		var tdrow = t.eq(i).find("td");
		for (var j = 0; j < tdrow.length; j++) {
			if(tdrow.eq(j).children().html() == "已发布"){
				t.eq(i).find("td").css({'border-bottom': '1px solid #f4daa3','background-color':'#fffaf0'});
			}
		}
	}
}

//查询
function searchFun(){
	var pipe = $("#lineDiv").children("a").attr("id") == "gdmc" ? "" : $("#lineDiv").children("a").attr("id");
	var segment = $("#segmentDiv").children("a").attr("id") == "jcgdmc" ? "" : $("#segmentDiv").children("a").attr("id");
	var data = {"taskName":$.trim($("#taskName").val()),"lineId":pipe,"segmentId":segment};
	$('#dataTable').selectDataAfterSetParm(data);
}

var tableOpt = {
		getCheckBox:function(id){
			var name = null == id ? 'checkAll' : 'checkSingle';
			var html = "<li style='list-style-type:none;' class='w5'><span class='table-ck'><span id='"+id+"' name='"+name+"' class='check-box selected' onclick=''><i></i></span></span></li>";
			return html;
		},
		
		getState:function(data){
			if("1" == data){
				return "未发布";
			}else if("2" == data){
				return "<p style='color:#FFAD00 !important'>已发布</p>";
			}
		},
		
		getOpt:function(data){
			var html = "<li style='list-style-type:none;' class='w15 no-right'><a href='javascript:void(0);' class='edit_00' onclick='getAddOrModify(\""+data+"\");'></a><a href='javascript:void(0);'  class='public_00' onclick='publishFun(\""+data+"\");'></a><a href='javascript:void(0);' class='download_00' onclick='downloadTaskFile(\""+data+"\");'></a></li>";
			return html;
		}
}


/* 日期格式化 */
Date.prototype.Format = function(fmt) {
    var o = {
        "M+" : this.getMonth() + 1, //月份
        "d+" : this.getDate(), //日
        "h+" : this.getHours(), //小时
        "m+" : this.getMinutes(), //分
        "s+" : this.getSeconds(), //秒
        "q+" : Math.floor((this.getMonth() + 3) / 3), //季度
        "S" : this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
    for ( var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1,
                    (RegExp.$1.length == 1) ? (o[k])
                            : (("00" + o[k])
                            .substr(("" + o[k]).length)));
    return fmt;
}

//删除
function deleteFun(ids){
	var pagePath = $("#pagePath").val();
	//获取所有name = childSelect的input
	var childBox = $("span[name=checkSingle]");
	if(ids == "mutiCheck"){
		var idsArr = new Array();
		var count = 0;
		for(var i= 0 ; i < childBox.length;i ++){
			if(childBox.eq(i).children().hasClass("active")){
				idsArr.push(childBox[i].id);
				count++;
			}
		}
		if(idsArr.length < 1){
			alert("请先勾选需要删除的任务");
			return ;
		}
		var idStr = idsArr.join();
		var delFlag = window.confirm("确定要删除吗");
		if(delFlag == true){
			var url = pagePath + "/cleanTask/cleanPipeLineManager/deleteFun.json?idStr="+idStr;
			$().invoke(url,{},[function(m,r){
				var delCount = r.delCount;
				var undelTask = r.undelTask;
				if(0 == delCount && "" != undelTask){
					tan0Dialog("已发布的任务不能删除。");
				}
				if(0 < delCount && "" == undelTask){
//					alert("已选择【"+count+"】条，成功删除【 "+delCount+" 】条");
					tan0Dialog("删除成功");
				}
				if(0 < delCount && "" != undelTask){
//					alert("已选择【"+count+"】条，成功删除【 "+delCount+" 】条。其中任务名为："+undelTask+" 的任务处于已发布状态,不允许删除");
					tan0Dialog("已发布的任务不能删除，其他任务已成功删除！  ");
				}
			}]);
		}
	}else{
		var delFlag = window.confirm("确定要删除吗");
		if(delFlag == true){
			var url = pagePath + "/cleanTask/cleanPipeLineManager/deleteFun.json?idStr="+ids;
			$().invoke(url,{},[function(m,r){
				if(r == 0){
					alert("该记录已经不允许删除");
				}else{
					alert("删除成功");
					window.location.href = pagePath + "/cleanTask/cleanPipeLineManager/goPiggingManagerPage.html";
				}
			}]);
		}
	}
}

//发布
function publishFun(ids){
	var pagePath = $("#pagePath").val();
	var childBox = $("span[name=checkSingle]");
	var count = 0;
	if(ids == "mutiCheck"){
		var idsArr = new Array();
		for(var i= 0 ; i< childBox.length ;i ++){
			if(childBox.eq(i).children().hasClass("active")){
				idsArr.push(childBox[i].id);
				count ++;
			}
		}
		if(idsArr.length < 1){
			alert("请先勾选需要发布的任务");
			return ;
		}
		var idStr = idsArr.join();
		var delFlag = window.confirm("确定要发布吗?");
		if(delFlag == true){
			var url = pagePath + "/cleanTask/cleanPipeLineManager/publishFun.json?idStr="+idStr;
			$().invoke(url,{},[function(m,r){
				alert("已选择【"+count+"】条，成功发布【 "+r+" 】条");
				window.location.href = pagePath + "/cleanTask/cleanPipeLineManager/goPiggingManagerPage.html";
			}]);
		}
	}else{
		var delFlag = window.confirm("确定要发布吗?");
		if(delFlag == true){
			var url = pagePath + "/cleanTask/cleanPipeLineManager/publishFun.json?idStr="+ids;
			$().invoke(url,{},[function(m,r){
				if(r == 0 ){
					alert("该记录不允许再次发布");
				}else{
					alert("发布成功");
					$("#"+ids).parent().parent().parent().parent().find("td:eq(7)").html("<p style='color:#FFAD00 !important'>已发布</p>");
					$("#"+ids).parent().parent().parent().parent().find("td").css({'border-bottom': '1px solid #f4daa3','background-color':'#fffaf0'});
					//$("#"+ids).parent().parent().parent().parent().find("td:eq(7)").css({'color':'#FFAD00 !important'});
				}
			}]);
		}
	}
}

//获取检测管段
function getInspSegment(lineId){
	$("#inspSegment").html('');
	var pagePath = $("#pagePath").val();
	var url = pagePath + "/cleanTask/cleanPipeLineManager/getInspSegment.json";
	$().invoke(url,{"lineId":lineId},[function(m,r){
		var inspSegment = r;
		var html='';
		$.each(inspSegment,function(i,evalue){
			html += "<li><a href='javascript:void(0);' id='"+ evalue.id+"'>"+ evalue.name+"</a></li>";
		});
		$("#segmentDiv").html("<a href='javascript:void(0);' id='jcgdmc'>管段名称</a><span></span>");
		$("#inspSegment").html(html);
	}]);
}

/**
 * 新增或修改
 * 2015-11-19
 */
function getAddOrModify(obj){
	var pagePath = $("#pagePath").val();
	var childBox = $("span[name=checkSingle]").children();
	var count = 0;
	var taskId = "";
	//未发布状态
	var status = false;
	//是否允许修改
	var isModify = false;
	var url0 = pagePath + "/cleanTask/cleanPipeLineManager/getTask.json";
	
	if( obj == "add"){
		window.location.href = pagePath + "/cleanTask/cleanPipeLineManager/addOrModify.html?taskId="+"";
	}else{
		taskId = obj;
		$().invoke(url0,{"taskId":taskId},[function(m,r){
			var st = r.staus;
			if(st != 1){
				status = true;
			}
		}],{async:false});
		if(status){
			alert("该任务不能修改");
			return;
		}else{
			window.location.href = pagePath + "/cleanTask/cleanPipeLineManager/addOrModify.html?taskId="+taskId;
		}
	}
}

/**
 * 
 * @Title: copyTask   
 * @Description: 复制任务
 * @param:       
 * @return: void      
 * @throws
 */
function copyTask(){
	var pagePath = $("#pagePath").val();
	var childBox = $("span[name=checkSingle]");
	var count = 0;
	var taskId = "";
	
	for(var i= 0 ; i < childBox.length;i ++){
		if(childBox.eq(i).children().hasClass("active")){
			if(count == 0){
				taskId = childBox[i].attributes.id.value;
			}
			count++;
		}
	}
	if(count != 1){
		alert("请勾选一条数据进行操作");
		return;
	}else{
    	var url =pagePath+ "/cleanTask/cleanPipeLineManager/copyTask.json";
    	$().invoke(url,{"taskId":taskId},[function(m,r){
			if("1" == r.copyCode){
				alert("该任务不能复制");
			}else{
				var task = r.pt;
				var line = r.pl;
				var segment = r.ps;
				var flag = r.f;
				var type = r.type;
				var pig = r.pigg;
				var cta = r.cta;
				var ct = r.ct;
				var ctId = r.ctId;
				if(null != task && undefined != task){
					$("#copyTaskName").val(task.name);
					$("#copyTaskId").val(task.id);
				}
				if(null != line && undefined != line){
					$("#copyPipeLine").html(line.name);
				}
				if(null != segment && undefined != segment){
					$("#copyPipeSegment").html(segment.inspSegmentName);
				}
				if(null != flag && undefined != flag && null != cta && undefined != cta){
					var toolShowHtml = "";
					$("#toolShow").html("");
					if(flag){
						var html = "";
						toolShowHtml += "<div class='sel w410 clearFix' style='margin-top:11px;width:100%;'>" +
								"<div class='dropdown-list' style='float:left;width:100%' >" +
								"<div class='drop-list drop-list-min' style='width:100%;height:28px;' id='copyCleanToolDiv'>" +
								"<div class='checked' style='width:91%;height:28px;'>" +
								"</div>" +
								"<span class='down-span'></span>" +
								"</div>" +
								"<ul class='select select-min none' style='width:293px;' id='copyCleanToolUl'>" +
								"</ul>" +
								"</div>" +
								"</div>";
						$("#toolShow").html(toolShowHtml);
						
						$("#copyCleanToolDiv").children("div").html("<a href='javascript:void(0);' id='"+ctId+"'>"+ct+"</a>");
//						$("#copyCleanToolUl").html("");
						$.each(cta,function(i,evalue){
							html += "<li><a href='javascript:void(0);' id='"+evalue.ID+"'>"+evalue.NAME+"</a></li>";
						});
						$("#copyCleanToolUl").html(html);
						xiala();
					}else{
						$("#toolShow").html("<input type='text' style='width:132px;float:left;' id='copyCt' value='"+ct+"'>");
					}
				}
				if(null != type && undefined != type){
//					$("#copyCleanType").html(type.name);
					$("#copyCleanType").html("<input type='hidden' value='"+type.ID+"'/>"+ type.name );
				}
				if(null != pig && undefined != pig){
					$("#copyFromPig").html(null == pig.fromValRoom || undefined == pig.fromValRoom ? "场站阀室" : pig.fromValRoom +"<input type='hidden' value='"+pig.fromPig+"'/>");
					$("#copyToPig").html(null == pig.toValRoom || undefined == pig.toValRoom ? "场站阀室" : pig.toValRoom +"<input type='hidden' value='"+pig.toPig+"'/>");
				}
				$("#copyRemark").val(task.createRemark);
				$("#copy").modal("show");
			}
    	}]);
	}
}

function copySave(){
	var taskId = $("#copyTaskId").val();
	var pagePath = $("#pagePath").val();
	var url = pagePath + "/cleanTask/cleanPipeLineManager/copySave.json";
	var taskName = $.trim($("#copyTaskName").val());
	var fromPig = $("#copyFromPig").children().val();
	var toPig = $("#copyToPig").children().val();
	var cleanTool = "";
	var planTime = $("#copyPlanTime").val();
	var remark = $("#copyRemark").val();
//	var type = $("#copyCleanType").children().attr("id");
	if("" == taskName || null == taskName || undefined == taskName){
		alert("请输入任务名称");
		return ;
	}
	if(undefined == $("#copyCt").val()){
		cleanTool = $("#copyCleanToolDiv").children().children().attr("id");
	}else if(null == $("#copyCt").val() || "" == $("#copyCt").val()){
		alert("请输入清管工具");
		return;
	}else{
		cleanTool = $("#copyCt").val();
	}
	if("" == planTime || null == planTime || undefined == planTime){
		alert("请选择计划清管时间");
		return;
	}
	if("" == fromPig || null == fromPig || undefined == fromPig){
		fromPig = "";
		alert("发球点不能为空");
		return;
	}
	if("" == toPig || null == toPig || undefined == toPig){
		toPig = "";
		alert("收球点不能为空");
		return;
	}
	/*if(undefined == type || null == type || "" == type){
		alert("清管类型数据异常，请刷新页面后重试");
		return;
	}*/
	if("" != taskId && null != taskId && undefined != taskId ){
		var data = {"taskId":taskId,"remark":remark,"cleanTool":cleanTool,"taskName":taskName,"planTime":planTime,"fromPig":fromPig,"toPig":toPig};
		$().invoke(url,data,[function(m,r){
			var msgCode = r.msgCode;
			if("1" == msgCode){
				alert("任务名称已经被使用，请重新输入");
				return; 
			}else if("ok" == msgCode){
				alert("保存成功");
				window.location.href = pagePath + "/cleanTask/cleanPipeLineManager/goPiggingManagerPage.html";
			}
		}]);
	}
}

function xiala(){
	$(".drop-list").each(function(i){
        var $select = $(this).parent().find(".select");
        var $checked = $(this).find(".checked");
        $checked.live('click',function(){
            if($select.hasClass('none')){
                $(".dropdown-list .select").addClass("none").eq(i).removeClass('none');
                $(".drop-list .checked").removeClass('current').eq(i).addClass('current');
            }else{
                $select.addClass('none');
                $(this).removeClass('current');
            }
            return false;
        });
        $(document).on('click', function(e){
            $select.addClass('none');
            $checked.removeClass('current');
            e.stopPropagation();
        });
    });
    $(".dropdown-list .select li").live('click',function(){
        var $txt = $(this).find('a').clone();
        var $checkedBox = $(this).parents('.dropdown-list').find('.checked');
        var $hiddenInput=$checkedBox.find('input');
        //$checkedBox.html($txt);
        $checkedBox.find("a").replaceWith($txt);
        if ($hiddenInput){
            $hiddenInput.val($txt.attr("vid"));
        }
        $(this).parent().addClass('none');
        $(this).parents('.dropdown-list').find('.checked').removeClass('current');
        return false;
    });

    //将下拉列表的位置固定
    $(".more-contents,.single-content,.tab-content").scroll(function(){
        var nScrollRight = $(this)[0].scrollLeft;
        $(this).find(".dropdown-list .select").css('marginLeft',-nScrollRight+'px').addClass("none");
        $(this).find(".drop-list .checked").removeClass('current');
        $(this).find(".max-select").find(".select").css('marginLeft',-nScrollRight-146+'px');
    });
}

/**
 * 下载任务附件
 */
function downloadTaskFile(taskId){
	var url = pagePath + "/cleanTask/cleanPipeLineManager/downloadTaskFile.json?taskId="+taskId;
	backgroundExport(url);
}

function closeAndHref(){
	$("#tan0").modal("hide");
	window.location.href = pagePath + "/cleanTask/cleanPipeLineManager/goPiggingManagerPage.html";
}